<?php
/**
 * @apiVersion 1.0.0
 * @api {POST} /wechat/Sms/sendMobileCode 003验证码发送OK
 * @apiDescription 验证码发送
 * @apiGroup Pub
 * @apiPermission 公众号
 * @apiParam {string} mobile 手机号码
 * @apiParamExample {json} 请求示例:
 * {
 *      "mobile": "15577778888",
 * }
 * @apiSuccess  {Int} code 状态
 * @apiSuccess  {Object} data 元数据
 * @apiSuccess  {String} msg 错误说明
 * @apiSuccessExample {json} 响应示例:
{

}

 * //操作未成功提示信息
 * {
 *      "code":0,
 *      "msg" :"错误说明"
 * }
 */

namespace app\wechat\controller;

use app\model\SmsLog;
use app\util\ReturnCode;
use app\util\Tools;


class Sms extends Base {

    //给所有用户发短信
    public function sendAllUser() {
        $userMobile = (new \app\model\User())->column('mobile');
        $id = $this->request->post()['id'];//模板id
        $params = json_decode($this->request->post()['params'],true);//参数
        if (empty($params)) {
            $params = [];
        }
        return $this->addSmsLog($id,$params,$userMobile);
    }

    /**
     * 将要发送的短信计入数据库
     */
    private function addSmsLog($id, $params, $mobileArr) {

        if (count($mobileArr) <= 0) {
            return Tools::buildReturn(ReturnCode::DB_SAVE_ERROR,'手机号不能为空');
        }

        $count = ceil(count($mobileArr) / config('sms.count'));

        $sendMobileArr = [];
        for ($i = 0; $i < $count; $i++) {
            $mobileArrs = array_slice($mobileArr,$i * config('sms.count'),config('sms.count'));
            $sendMobileArr[$i]['smsMobile'] = json_encode($mobileArrs);
            $sendMobileArr[$i]['smsParams'] = json_encode($params);
            $sendMobileArr[$i]['smsParamsID'] = $id;
            $sendMobileArr[$i]['sended'] = 0;
            $sendMobileArr[$i]['smsCount'] = count($mobileArrs);
        }

        $model = new SmsLog();

        $res = $model->saveAll($sendMobileArr);

        if (!empty($res)) {
            return $this->buildSuccess([]);
        } else {
            return $this->buildFailed(ReturnCode::ADD_FAILED,'失败');
        }

    }

    public  function sendMobile(){
        $params = $this->request->post()['params'];//发送内容
        $id = $this->request->post()['codeID'];//模板id
        $mobile = $this->request->post()['mobile'];//手机号
        $result = (new \app\util\SMS)->sendMobileCode($mobile,$id,$params);
        return  $result;
    }

    public  function getCodeID(){
        $arr = config('sms.codeIDarray');
        return  $this->buildSuccess($arr);
    }

    //发送验证码短信
    public  function sendMobileCode(){
        $id = 1;//模板id
        $mobile = $this->request->post()['mobile'];//手机号
        $result = (new \app\util\SMS)->sendMobileCode($mobile,$id,'');
        return  $result;
    }



}
